package com.ruoyi.system.vo;

import org.apache.commons.io.FileUtils;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.IOException;

/**
 * 〈base64转文件〉
 *
 * @author LJP
 * @create 2019/5/9
 * @since 1.0.0
 */
public class Base64ToFileUtil {

    private static Logger logger = LoggerFactory.getLogger(Base64ToFileUtil.class);

    /**
     * @param filePath
     * @param base64Str
     */
    public static void base64ToFile(String base64Str, String filePath) {

//        String imgStr = base64.encode(base64Str);
        System.err.println(base64Str.length());
        try {
            byte[] b = Base64.decode(base64Str);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
//            String imgFilePath = "d://yyyyy.png";
            FileUtils.writeByteArrayToFile(new File(filePath), b);

            /**
             * 生成缩略图
             * 若图片横比200小，高比300小，不变
             * 若图片横比200小，高比300大，高缩小到300，图片比例不变
             * 若图片横比200大，高比300小，横缩小到200，图片比例不变
             * 若图片横比200大，高比300大，图片按比例缩小，横为200或高为300
             */
            System.err.println("OK");
        } catch (Exception e) {

            System.out.println("error");
        }
    }

    /**
     * base64 转 Multipart
     *
     * @param base64
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStr = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStr[1]);

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return null;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return null;
        } catch (ArrayIndexOutOfBoundsException a) {
            logger.error(a.getMessage());
            return null;
        }
    }

    public static byte[] base64ToByte(String base64) {
        try {
            String[] baseStr = base64.split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] buffer = new byte[0];
            buffer = decoder.decodeBuffer(baseStr[1]);
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] < 0) {// 调整异常数据
                    buffer[i] += 256;
                }
            }
            return buffer;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return null;
        } catch (ArrayIndexOutOfBoundsException a) {
            logger.error(a.getMessage());
            return null;
        }
    }

}
